<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>bubbleSort</title>
</head>

<body>
  <script>
    // 比较次数O(N^2)
    // 交换次数O(N^2)
    function swap(array, a, b) {
      [array[a], array[b]] = [array[b], array[a]]
    }

    function bubbleSort(array) {
      let length = array.length;
      for (let i = length - 1; i >= 0; i--) {
        for (let j = 0; j < i; j++) {
          if (array[j] > array[j + 1]) {
            swap(array, j, j + 1)
          }
        }
      }
      return array
    }

    let arr = [123, 14, 521, 8, 31, 943, 19, 56, 241]
    console.log(bubbleSort(arr))
  </script>
</body>

</html>